#!/bin/dash
set -e

skip=false

EtcDir=/etc
RcsUrl=http://sysrcs.googlecode.com/git
RecipeExt=.recipe
SystemExt=.system
PkgMkrCfg=pkgmkr.cfg
PkgFileExt=pkg.txz
GlobalSQLite=global.sqlite

MakeEnvDirs() {
	if [ ! -d $RcsDir ]; then
		mkdir -p $RcsDir
	fi
	if [ ! -d $SrcDir/$name ]; then
		mkdir -p $SrcDir/$name
	fi
	if [ ! -d $PkgDir/$name ]; then
		mkdir -p $PkgDir/$name
	fi
}

FetchScript() {
	RcsFile=$RcsDir/$name/$name$RecipeExt
	RcsUrlDir=$RcsUrl/$name
	if [ ! -f $RcsFile ]; then
		cd $RcsDir
		echo "info: fetching recipe: $name"
		wget -nv -r -l1 -np -nH --cut-dirs=1 --reject=html $RcsUrlDir
		echo "      done"
		cd $BldDir
	fi
}

GetSrcFile() {
	if [ ! -f $TmpDir/$srcfile ]; then
		cd $TmpDir
		echo "      downloading: $srcfile"
		wget -nv $u
		cd $BldDir
	fi
}

ExtractFile() {
	echo "      extracting: $srcfile"
	cd $TmpDir
	tar -C $SrcDir/$name -xf $srcfile
	cd $BldDir
}

CompileSrc() {
	cd $src/$p
	Src
	cd $BldDir
}

CompilePkg() {
	cd $src/$p
	Pkg
	cd $BldDir
}

ChkFileList() {
	for i in $lst; do
		echo $i
	done
}

CreateDBase() {
	if [ ! -f $SysDir/$GlobalSQLite ]; then
		sqlite3 $SysDir/$GlobalSQLite "create table pkg (name text primary key, ver text, grp text, lst text, sys text);"
	fi
}

InsertDBase() {
	CreateDBase
	sqlite3 $SysDir/$GlobalSQLite "delete from pkg where name = '$n';"
	sqlite3 $SysDir/$GlobalSQLite "insert into pkg(name, ver, grp, lst, sys) values('$n', '$v', '$g', '$lst', '$sys');"
}

CompressPkg() {
	rm -f $pkg$shr/info/dir

	echo "      creating filelist"
	cd $pkg

	touch ../filelist.txt
	for i in $(find -type f | sort); do
		echo $i >> ../filelist.txt
	done
	sed -i -e 's/.\//\//' ../filelist.txt
	lst=$(cat ../filelist.txt)
	rm ../filelist.txt

	echo "      compressing file"
	if [ ! -d $SysDir/$g ]; then
		mkdir -p $SysDir/$g
	fi

	pkgfile=$n-$v-$PkgFileExt
	if [ -f $SysDir/$g/$pkgfile ]; then
		rm -f $SysDir/$g/$n-[0-9]*
	fi

	fakeroot tar -cJf $SysDir/$g/$pkgfile ./

	sys=""
	SysFile=$RcsDir/$name/$name$SystemExt
	if [ -f $SysFile ]; then
		sys=$(cat $SysFile)
	fi

	#ChkFileList
	InsertDBase
	cd $BldDir
}

CleanEnvDir() {
	rm -rf $PkgDir/$name
	rm -rf $SrcDir/$name
}

MakePackage() {
    pkg=$PkgDir/$name
	rcs=$RcsDir/$name
    src=$SrcDir/$name

	MakeEnvDirs
	FetchScript

	. $RcsDir/$name/$name$RecipeExt
	srcfile=$(basename $u)
	if [ -z $p ]; then
		p=$n-$v
	fi

	echo "info: preparing source: $n-$v"
	GetSrcFile
	ExtractFile
	echo "      done"

	export CHOST CFLAGS CXXFLAGS LDFLAGS MAKEFLAGS
	echo "info: compiling source: $n-$v"
	if [ $skip == true ]; then
		CompilePkg
	else
		CompileSrc
		CompilePkg
	fi
	echo "      done"

	echo "info: creating package: $n-$v"
	CompressPkg
	CleanEnvDir
	echo "      done"	
}

. $EtcDir/$PkgMkrCfg

if [ -z $1 ]; then
	echo "warn: missing flag"
	exit 0
fi

for i in $@; do
	if [ $i == "--skip-src" ]; then
		skip=true
	else
		name=$i
		MakePackage
	fi
done
